package com.example.testmediaplayer;

import java.io.IOException;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.res.Resources;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;

public class MainActivity extends Activity {

	private MediaPlayer mediaPlayer;
	private final Handler handler = new Handler();
	SeekBar seekBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button mPlay = (Button) findViewById(R.id.button_play);
		Button mStop = (Button) findViewById(R.id.button_stop);
		Button mPause = (Button) findViewById(R.id.button_pause);
		
		mPlay.setOnClickListener(playListener);
		mStop.setOnClickListener(stopListener);
		mPause.setOnClickListener(pauseListener);
		
		seekBar = (SeekBar) findViewById(R.id.seek_bar);
        seekBar.setOnTouchListener(seekListener);
		
	}
	
	private OnTouchListener seekListener = new OnTouchListener() {
		@Override 
    	public boolean onTouch(View v, MotionEvent event) {
			if (mediaPlayer == null) {
				return false;
			}
			
			if(mediaPlayer.isPlaying()) {
		    	SeekBar sb = (SeekBar)v;
				mediaPlayer.seekTo(sb.getProgress());
			}
    		return false; 
		}
	};

	private OnClickListener playListener = new OnClickListener() {
		public void onClick(View v) {
			if (mediaPlayer == null) {
				mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.ring);
				seekBar.setMax(mediaPlayer.getDuration());
			}
			
			mediaPlayer.start();
			startPlayProgressUpdater();
		}
	};
	
	private OnClickListener stopListener = new OnClickListener() {
		public void onClick(View v) {
			if (mediaPlayer == null) {
				return;
			}
			
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
			seekBar.setProgress(0);
		}
	};
	
	private OnClickListener pauseListener = new OnClickListener() {
		public void onClick(View v) {
			if (mediaPlayer == null) {
				return;
			}
			
			mediaPlayer.pause();
		}
	};
	
	public void startPlayProgressUpdater() {
		Log.w("run", "startPlayProgressUpdater");
		if (mediaPlayer == null) {
			return;
		}
		
		seekBar.setProgress(mediaPlayer.getCurrentPosition());
		
		if (mediaPlayer.isPlaying()) {
			Runnable notification = new Runnable() {
		        public void run() {
		        	startPlayProgressUpdater();
				}
		    };
		    handler.postDelayed(notification, 1000);
    	} 
    } 
}
